#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
系统管理器模块
提供系统级操作功能
"""

import os
import subprocess
from typing import Optional, List

from ..core.utils import (
    logger,
    run_command,
    is_windows,
    confirm_action,
    get_input_with_default
)

class SystemManager:
    """系统管理功能类"""
    
    def generate_and_sync_ssh_key(self):
        """生成SSH密钥并同步到远程服务器"""
        # Windows环境下不支持此功能
        if is_windows():
            logger.error("此功能在Windows环境下不受支持")
            return
            
        remote_ip = get_input_with_default("输入远程服务器的IP地址", "")
        remote_user = get_input_with_default("输入远程服务器的用户名", "root")
        remote_port = get_input_with_default("输入远程服务器的端口", "22")
        
        if not remote_ip:
            logger.error("远程服务器IP地址不能为空")
            return
            
        try:
            # 生成SSH密钥对（如果没有现有密钥）
            ssh_dir = os.path.expanduser("~/.ssh")
            private_key_path = os.path.join(ssh_dir, "id_rsa")
            
            if not os.path.exists(ssh_dir):
                os.makedirs(ssh_dir)
                
            if not os.path.exists(private_key_path):
                logger.info("正在生成SSH密钥对...")
                run_command(["ssh-keygen", "-t", "rsa", "-b", "2048", "-f", private_key_path, "-N", ""])
            else:
                logger.info("SSH密钥对已存在，跳过密钥生成")
                
            # 同步公钥到远程服务器
            logger.info(f"正在将SSH公钥同步到 {remote_user}@{remote_ip}...")
            run_command(["ssh-copy-id", "-p", remote_port, f"{remote_user}@{remote_ip}"])
            
            logger.info(f"SSH公钥已成功同步到 {remote_ip}")
        except Exception as e:
            logger.error(f"生成或同步SSH密钥失败: {e}")
    
    def add_ssh_config(self):
        """为指定SSH连接修改默认连接端口"""
        ip_address = get_input_with_default("请输入要添加的IP地址", "")
        port = get_input_with_default("请输入要添加的端口", "22")
        
        if not ip_address:
            logger.error("IP地址不能为空")
            return
            
        # 定义SSH配置文件路径
        if is_windows():
            # Windows上的用户目录
            ssh_config_path = os.path.expanduser(os.path.join("~", ".ssh", "config"))
        else:
            # Linux系统处理多个用户
            users = ["root", "postgres"]
            for user in users:
                if user == "postgres":
                    ssh_config_path = os.path.expanduser(f"/home/{user}/.ssh/config")
                else:
                    ssh_config_path = os.path.expanduser(f"/{user}/.ssh/config")
                    
                self._add_ssh_config_entry(ssh_config_path, ip_address, port)
            return
            
        # Windows只处理当前用户
        self._add_ssh_config_entry(ssh_config_path, ip_address, port)
    
    def _add_ssh_config_entry(self, ssh_config_path: str, ip_address: str, port: str):
        """添加SSH配置文件条目"""
        # 创建SSH配置文件（如果不存在）
        ssh_dir = os.path.dirname(ssh_config_path)
        if not os.path.exists(ssh_dir):
            try:
                os.makedirs(ssh_dir, exist_ok=True)
            except Exception as e:
                logger.error(f"创建目录 {ssh_dir} 时出错: {e}")
                return
                
        if not os.path.exists(ssh_config_path):
            try:
                with open(ssh_config_path, "w") as f:
                    f.write("")  # 创建空文件
            except Exception as e:
                logger.error(f"创建文件 {ssh_config_path} 时出错: {e}")
                return
                
        # 检查是否已经存在相同的Host配置
        try:
            with open(ssh_config_path, "r") as f:
                lines = f.readlines()
                
            # 检查Host是否已存在
            host_exists = any(line.strip() == f"Host {ip_address}" for line in lines)
            
            if host_exists:
                logger.info(f"Host {ip_address} 已存在于 {ssh_config_path} 中，未进行任何更改")
            else:
                # 添加新的Host和Port配置
                with open(ssh_config_path, "a") as f:
                    f.write(f"\nHost {ip_address}\n")
                    f.write(f"    Port {port}\n")
                    
                logger.info(f"已成功添加到 {ssh_config_path}:\nHost {ip_address}\n    Port {port}")
        except Exception as e:
            logger.error(f"修改 {ssh_config_path} 时出错: {e}") 